package mobile.util;

import java.io.File;
import java.io.IOException;

import com.alibaba.fastjson.JSONObject;
import com.aton.config.AppMode;
import com.aton.config.AppMode.Mode;
import com.aton.util.QnCloudUtil.QnFileBucket;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

public class QiniuUploadTool {
	
	// 设置好账号的ACCESS_KEY和SECRET_KEY
	private static String ACCESS_KEY = com.aton.config.Config.QN_ACCESS_KEY;
	private static String SECRET_KEY = com.aton.config.Config.QN_SECRET_KEY;

	// 密钥配置
	private static Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);

	// 第二种方式: 自动识别要上传的空间(bucket)的存储区域是华东、华北、华南。
	private static Zone z = Zone.autoZone();
	private static Configuration c = new Configuration(z);

	// 创建上传对象
	private static UploadManager uploadManager = new UploadManager(c);
	// 简单上传，使用默认策略，只需要设置上传的空间名就可以了
	private static String getUpToken() {
		String bucket = null;
		if (AppMode.get().mode == Mode.TEST) {
			bucket = QnFileBucket.TEST.code;
		} else if (AppMode.get().mode == Mode.ONLINE) {
			bucket = QnFileBucket.ONLINE_PUBLIC.code;
		} else {
			bucket = QnFileBucket.DEV.code;
		}
		return auth.uploadToken(bucket);
	}

	public static String upload(File file) throws IOException {
		String filePath = null;
		try {
			// 调用put方法上传
			Response res = uploadManager.put(file.getPath(), file.getName(), getUpToken());
			// 打印返回的信息
			filePath = new JsonParser().parse(res.bodyString()).getAsJsonObject().get("key").getAsString();
		} catch (QiniuException e) {
			Response r = e.response;
			// 请求失败时打印的异常的信息
			play.Logger.error("上传文件到七牛时出错，错误信息:%s", r.toString());
			try {
				// 响应的文本信息
				play.Logger.error("上传文件到七牛时出错，响应信息为:%s", r.bodyString());
			} catch (QiniuException e1) {
			}
		}
		return filePath;
	}
}
